package org.beetlframework.util;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

/**
 * 实现请求参数与javaBean之间的转换
 * @author yangtonggan
 * @date 2016-10-4
 */
public class BeanUtil {
	
    /**
     * 获取bean实例
     * @param request
     * @param t
     * @return
     */
	public static <T> T getBean(HttpServletRequest request, Class<T> t) {		
		List<String> paraNames = Collections.list(request.getParameterNames());		
		Map<String,Object> map = new HashMap<String,Object>();	
		Field[] fields = t.getDeclaredFields();
		for(Field f : fields ){
			String key = f.getName();
			if(paraNames.contains(key)){				
				map.put(key, request.getParameter(key));
			}			
		}
		T bean = createInstance(t);
		Map2BeanUtil.toBean(map, bean);
		return bean;
	}
	
	/**
	 * 根据类创建实例
	 * @param objClass
	 * @return
	 */
	private static <T> T createInstance(Class<T> objClass) {
		try {
			return objClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
